
const { randomUUID } = require("crypto");
const { saveData, queryList, getDetail, deleteDocument } = require("../../controller/development/codeGengeration-conroller");
const { serverError } = require("../../utils");
const { emptyCheck } = require("../../utils/checkEmpty");
const pageSizeList = require("../../utils/slicePageSize");
const { generationCode } = require("../../controller/development/util");
const path = require("path");
const fs = require('fs');
const archiver = require('archiver');

/**
 * @description codeGengeration代码生成 API路由
 * @author 韩
 */
const router = require("koa-router")()
router.prefix("/dev/codeGengeration");

// 添加或编辑
router.post("/save", async (ctx, next) => {
    try {

        const {
            id = undefined, title, modelData, remark, componentName,tableName
        } = ctx.request.body
        const check = emptyCheck({ title })
        if (check.code !== 0) {
            ctx.body = check
        } else {
            const res = await saveData({
                id, title, remark, modelData, componentName,tableName

            })
            ctx.body = res
        }
    } catch (error) {
        console.log(error)
        ctx.body = serverError
    }
})

// // 查询列表
router.post("/list", async (ctx, next) => {
    try {
        const { current, pageSize, title } = ctx.request.body;
        const res = await queryList({
            current, pageSize, title
        })
        ctx.body = res
    } catch (error) {
        console.log(error)
        ctx.body = serverError
    }

})


// // 删除
router.delete("/delete", async (ctx, next) => {
    try {
        const id = ctx.query.id || undefined;
        if (!id) {
            ctx.body = {
                code: '0011',
                msg: "未选择需要删除的数据"
            }
        }
        else {
            const res = await deleteDocument({ id })
            ctx.body = res;
        }
    } catch (error) {
        ctx.body = serverError
    }
})

// // 查看详情
router.get("/detail", async (ctx, next) => {
    try {
        const id = ctx.query.id || undefined;
        const check = emptyCheck({ id })
        if (check.code !== 0) {
            ctx.body = check;
        } else {
            const res = await getDetail({ id: id })
            ctx.body = res;
        }

    } catch (error) {
        ctx.body = serverError
    }
})



function zipDirectory(source, out) {
    const archive = archiver('zip', { zlib: { level: 9 } }); // 设置压缩级别
    const stream = fs.createWriteStream(out);

    return new Promise((resolve, reject) => {
        archive
            .directory(source, false) // 添加目录到归档，第二个参数为是否包括根目录
            .on('error', err => reject(err))
            .pipe(stream);

        stream.on('close', () => resolve());
        archive.finalize();
    });
}


router.get("/download", async (ctx, next) => {
    try {
        await generationCode({
            id: ctx.query.id
        })


        let fileStream = null;
        // 获取当前文件的目录
        const currentDir = __dirname;
        // 构建 temp 目录下的 src 子目录的路径
        const dirPath = path.join(currentDir, '..', "..", 'template', 'src');
        const zipFilePath = path.join(currentDir, '..', "..", 'template', 'output.zip');
        await zipDirectory(dirPath, zipFilePath)
            .then(() => {
                const currentDir = __dirname;
                const filePath = path.join(currentDir, "..", "..", "template", 'output.zip'); // 使用绝对路径或相对路径
                if (!fs.existsSync(filePath)) {
                    ctx.status = 404;
                    ctx.body = '文件不存在';
                    return;
                }
                fileStream = fs.createReadStream(filePath);
            })
            .catch(err => {
                console.error('压缩失败:', err)
            });


        ctx.body = fileStream

    } catch (error) {
        console.error('Error:', error);
        ctx.status = 500;
        ctx.body = '服务器内部错误';
    } finally {

    }
})





module.exports = router